<template>
  <div class="leaflet-top leaflet-right">
    <div class="leaflet-control leaflet-bar map-toolbar" @click.stop="">
      <div v-for="menu in toolbarMenus" :key="menu.C_WEB_SYSMENU_ID" class="toolbar-item">
        <!-- 有子菜单且子菜单数量>1的项 -->
        <el-dropdown v-if="menu.child && menu.child.length > 1" trigger="click" @command="handleCommand">
          <el-button type="text" :title="menu.MENUNAME">
            <i :class="['iconfont', `icon-a-${menu.ICONNAME || 'tuceng'}`]"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item v-for="child in menu.child" :key="child.C_WEB_SYSMENU_ID" :command="child.COMMANDNAME">
              <i :class="['iconfont', `icon-a-${child.ICONNAME || 'tuceng'}`]" style="margin-right: 8px;"></i>
              {{ child.MENUNAME }}
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>

        <!-- 有子菜单但只有1个的项 - 直接显示为按钮 -->
        <el-button v-else-if="menu.child && menu.child.length === 1" type="text" :title="menu.child[0].MENUNAME" @click.stop="handleCommand(menu.child[0].COMMANDNAME)">
          <i :class="['iconfont', `icon-a-${menu.child[0].ICONNAME || 'tuceng'}`]"></i>
        </el-button>

        <!-- 没有子菜单的项 -->
        <el-button v-else type="text" :title="menu.MENUNAME" @click.stop="handleCommand(menu.COMMANDNAME)">
          <i :class="['iconfont', `icon-a-${menu.ICONNAME || 'tuceng'}`]"></i>
        </el-button>
      </div>
    </div>
  </div>
</template>
<script>
import { getMapModuleTool, processToolbarMenus } from '../../../widgets/mapUtils'
import { sessionStorage } from '@/deps/utils'
const weldWhiteArr = ['C_PRO_WELDBOX']
const pipeWhiteArr = ['C_MID_PIPELINE']
export default {
  name: 'MapToolbar',
  props: {
    menus: {
      type: Array,
      default: () => []
    },
    filterOptions: {
      type: Object,
      default: () => ({})
    },
    webmoduleId: {
      type: Number,
      default: 60
    }
  },
  data() {
    return {
      toolbarMenus: [],
      weldboxFeature: null,
      pipeFeature: null,
      blackIds: [62, 63],
      viewHistory: [],
      currentViewIndex: -1,
      isViewChanging: false,
      maxHistoryLength: 20 // 添加历史记录最大长度限制
    }
  },
  async created() {
    await this.initToolbar()
    if (!this.blackIds.includes(this.webmoduleId)) {
      this.$bus.$on('CHANGE_LAYER_INFO_BY_RIGHT_SELECT', this.handleLayerInfoChange)
    }
  },
  beforeDestroy() {
    this.mapObj && this.mapObj.off('moveend', this.moveendHandler)
    if (!this.blackIds.includes(this.webmoduleId)) {
      this.weldboxFeature = null
      this.$bus.$off('CHANGE_LAYER_INFO_BY_RIGHT_SELECT', this.handleLayerInfoChange)
    }
  },
  methods: {
    setMapObj(mapObj) {
      this.mapObj = mapObj
      this.mapObj.on('moveend', this.moveendHandler)
    },
    moveendHandler() {
      if (this.isViewChanging) {
        this.isViewChanging = false
        return
      }
      const center = this.mapObj.getCenter()
      const zoom = this.mapObj.getZoom()
      const currentView = { center, zoom }
      // 只有当视图确实发生变化时才记录
      if (this.viewHistory.length === 0 || !center.equals(this.viewHistory[this.currentViewIndex].center) || zoom !== this.viewHistory[this.currentViewIndex].zoom) {
        // 如果当前不是最后一个视图，则截断后面的历史
        if (this.currentViewIndex < this.viewHistory.length - 1) {
          this.viewHistory = this.viewHistory.slice(0, this.currentViewIndex + 1)
        }
        // 添加新记录并限制历史记录长度
        this.viewHistory.push(currentView)
        if (this.viewHistory.length > this.maxHistoryLength) {
          this.viewHistory.shift()
        }
        this.currentViewIndex = this.viewHistory.length - 1
      }
    },
    async initToolbar() {
      const rawMenus = await getMapModuleTool(this.webmoduleId)
      // 使用传入的menus或从接口获取的rawMenus
      const sourceMenus = this.menus.length > 0 ? this.menus : rawMenus
      // 应用过滤配置
      this.toolbarMenus = processToolbarMenus(sourceMenus, this.filterOptions)
    },
    handleLayerInfoChange(d) {
      this.weldboxFeature = null
      this.pipeFeature = null
      if (weldWhiteArr.includes(d.properties.LAYERNAME)) {
        this.weldboxFeature = d
      } else if (pipeWhiteArr.includes(d.properties.LAYERNAME)) {
        this.pipeFeature = d
      }
    },
    fullscreen(element) {
      if (document.mozFullScreenEnabled) {
        return Promise.reject(new Error('全屏模式被禁用'))
      }
      let result = null
      if (element.requestFullscreen) {
        result = element.requestFullscreen()
      } else if (element.mozRequestFullScreen) {
        result = element.mozRequestFullScreen()
      } else if (element.msRequestFullscreen) {
        result = element.msRequestFullscreen()
      } else if (element.webkitRequestFullscreen) {
        result = element.webkitRequestFullScreen()
      }
      return result || Promise.reject(new Error('不支持全屏'))
    },
    exitFullscreen() {
      if (document.exitFullscreen) {
        // 标准写法
        document.exitFullscreen()
      } else if (document.mozCancelFullScreen) {
        // Firefox 浏览器
        document.mozCancelFullScreen()
      } else if (document.webkitExitFullscreen) {
        // Chrome 和 Safari
        document.webkitExitFullscreen()
      } else if (document.msExitFullscreen) {
        // IE11
        document.msExitFullscreen()
      }
    },
    // 在handleCommand方法中添加视图切换逻辑
    handleCommand(command) {
      switch (command) {
        case 'beforeView':
          if (this.currentViewIndex > 0) {
            this.isViewChanging = true
            this.currentViewIndex--
            const { center, zoom } = this.viewHistory[this.currentViewIndex]
            this.mapObj.setView(center, zoom, { animate: true })
          }
          break
        case 'afterView':
          if (this.currentViewIndex < this.viewHistory.length - 1) {
            this.isViewChanging = true
            this.currentViewIndex++
            const { center, zoom } = this.viewHistory[this.currentViewIndex]
            this.mapObj.setView(center, zoom, { animate: true })
          }
          break
        case 'fullScreen':
          // 全屏逻辑
          if (!document.fullscreenElement) {
            this.fullscreen(document.documentElement)
          } else {
            this.exitFullscreen(document.documentElement)
          }
          break
        case 'weldbox':
          console.error(this.weldboxFeature)
          if (!this.weldboxFeature) {
            this.$message.warning('请先选择接续盒')
            return
          }
          break
        case 'pipe':
          console.error(this.pipeFeature)
          if (this.pipeFeature) {
            // 存储 featureData
            sessionStorage('pipe_feature', this.pipeFeature)
          } else {
            this.$message.warning('请先选择管道')
            return
          }
          break
        // 其他命令处理...
      }
      console.error('command', command)
      const EMIT_COMMAND = {
        60: ['importcad_room', 'openPrj', 'refreshMap', 'removeHightlight', 'measureDistance', 'measureArea', 'clearLayers', 'pipe', 'choseData', 'weldbox', 'switchbox', 'roomPlateDesign', 'moveAction', 'editAction', 'deleteAction'],
        61: ['choseitem', 'batchweldconnitem', 'deleteconnitem', 'batchdeleteweldconnitem', 'testFreshMap'],
        64: ['cabEquipDesign']
      }
      if (this.blackIds.includes(this.webmoduleId) || EMIT_COMMAND[this.webmoduleId].includes(command)) {
        this.$emit('command', command)
      }
    }
  }
}
</script>

<style scoped>
.map-toolbar {
  background: rgba(255, 255, 255, 0.8);
  border-radius: 4px;
  display: flex;
  flex-wrap: wrap;
  border: 0;
}

.toolbar-item {
  margin: 2px;
}

.el-button {
  padding: 4px;
  font-size: 16px;
}

.el-button--text {
  color: #333;
}

.el-button:hover {
  background-color: #f0f0f0;
}

.iconfont {
  font-size: 13px;
}
</style>
